package com.example.kotlinlearningproject

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.example.kotlinlearningproject.audioplayer.SoundPoolPlayer
import com.example.kotlinlearningproject.databinding.ActivityMainBinding
import com.example.kotlinlearningproject.network.DownloadHandler
import com.example.kotlinlearningproject.network.NetworkHelper
import com.example.kotlinlearningproject.utils.Const
import com.example.kotlinlearningproject.utils.DeviceIdUtil
import com.github.promeg.pinyinhelper.Pinyin
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict

private const val TAG = "MainActivity"

class MainActivity : ComponentActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var soundPoolPlayer: SoundPoolPlayer
    private lateinit var mediaPlayer: MediaPlayer

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 1.SoundPool播放mp3
        soundPoolPlayer = SoundPoolPlayer()
        soundPoolPlayer.preload(assets)
        binding.btnPlay.setOnClickListener { soundPoolPlayer.playIKnowMp3() }

        // 2.测试tinypinyin
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(this)))
        binding.btnTinyPinyin.setOnClickListener{
            val pinyin = Pinyin.toPinyin("这里是中国", "")
            Log.d(TAG, "拼音转为: ${pinyin} **********")
        }

        // 3.使用retrofit调用翻译接口
        binding.btnTranslate.setOnClickListener{NetworkHelper().translate()}

        // 4.MediaPlayer播放线上音频
        mediaPlayer = MediaPlayer()
        binding.btnMediaPlay.setOnClickListener{
            if(mediaPlayer.isPlaying) {
                mediaPlayer.stop()
            } else {
                mediaPlayer.reset() //多次点击需要重置
                mediaPlayer.setDataSource(Const.AUDIO_URL)
                // 同步准备并播放
                mediaPlayer.prepare()
                Log.d(TAG, "prepare完成**********")
                mediaPlayer.start()
                Log.d(TAG, "播放**********")
            }
        }
        // 5.MediaPlayer异步播放线上音频
        binding.btnMediaPlay2.setOnClickListener{
            if(mediaPlayer.isPlaying) {
                mediaPlayer.stop()
            } else {
                mediaPlayer.reset() //多次点击需要重置
                mediaPlayer.setDataSource(Const.AUDIO_URL)
                // 同步准备并播放
                mediaPlayer.prepareAsync()
                mediaPlayer.setOnPreparedListener {
                    mediaPlayer.start()
                }
                mediaPlayer.setOnCompletionListener {
                    Log.d(TAG, "播放完成**********")
                }
            }
        }
        // 6.获取设备唯一标识
        val android_device_id =
            Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
        binding.tvShowMsg.text = ("DEVICEID: "+DeviceIdUtil.getMEID()+"\n"
                +"Mac: "+DeviceIdUtil.getMacAddress(this)+"\n"
                +"Android Id: "+android_device_id+"\n"
                +"UniqueID: "+DeviceIdUtil.getUniqueID(this));
        // 7.下载一个mp3文件，存放在
        binding.btnDownload.setOnClickListener {requestPermission()}
    }

    private var permissionLauncher: ActivityResultLauncher<Array<String>> = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { result ->
        var isDenyAll = true
        result.entries.forEach {
            isDenyAll = isDenyAll and it.value
        }

        if (isDenyAll) {
            // 权限没有得到
            Toast.makeText(this, "没有授权！", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "已授权！", Toast.LENGTH_SHORT).show()
            // 下载音频
            DownloadHandler(this).downloadAudio(Const.AUDIO_URL)
        }
    }

    private fun requestPermission() {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED
        ) {
            Toast.makeText(this, "已授权！", Toast.LENGTH_SHORT).show()
            // 下载音频
            DownloadHandler(this).downloadAudio(Const.AUDIO_URL)
        } else {
            permissionLauncher.launch(
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
    }
}
